package com.wayne.factory;

import com.wayne.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.InvocationHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Proxy;
@Component("proxyFactory")
public class ProxyFactory {

  @Autowired
  private TransactionManager transactionManager;

  /**
   * JDK 动态代理
   *
   * @param obj
   * @return
   */
  public Object getJdkProxy(Object obj) {
    return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), (o, method, args) -> {
      Object result = null;
      // 开启事务手动提交
      transactionManager.beginTransaction();
      try {
        result = method.invoke(obj, args);
        // 提交事务
        transactionManager.commit();
      } catch (Exception e) {
        // 回滚事务
        transactionManager.rollback();
        throw e;
      }
      return result;
    });
  }

  /**
   * cglib 动态代理
   *
   * @param obj
   * @return
   */
  public Object getCglibProxy(Object obj) {
    return Enhancer.create(obj.getClass(), (InvocationHandler) (o, method, objects) -> {
      Object result = null;
      // 开启事务手动提交
      transactionManager.beginTransaction();
      try {
        result = method.invoke(obj, objects);
        // 提交事务
        transactionManager.commit();
      } catch (Exception e) {
        // 回滚事务
        transactionManager.rollback();
        throw e;
      }
      return result;
    });
  }
}
